import { useEffect } from "react";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { clearProfile } from "@/store/modules/user";
export const useAxiosWithAuth = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const { token } = useSelector((state: any) => state.user.profile);
  const request = axios.create({
    baseURL: " http://pcapi-xiaotuxian-front-devtest.itheima.net/",
    timeout: 10000,
  });
  useEffect(() => {
    const requestInterceptor = request.interceptors.request.use(
      (config) => {
        if (token) {
          config.headers["Authorization"] = `Bearer ${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    const responseInterceptor = request.interceptors.response.use(
      (response) => {
        return response.data;
      },
      (error) => {
        if (error.response && error.response.status === 401) {
          dispatch(clearProfile());
          const fullPath = encodeURIComponent(
            (location.pathname + location.search) as string
          );
          navigate("/login?redirectUrl=" + fullPath);
        }
        return Promise.reject(error);
      }
    );

    // Cleanup 拦截器
    return () => {
      request.interceptors.request.eject(requestInterceptor);
      request.interceptors.response.eject(responseInterceptor);
    };
  }, [token, request]);

  return request;
};
